package com.miplus.ccrm.sms.aicall;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson2.util.UUIDUtils;
import com.mashape.unirest.http.Headers;
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;
import com.miplus.ccrm.common.CmdResVo;
import com.miplus.ccrm.common.EnumRCode;
import com.miplus.ccrm.common.JPubUtils;
import com.miplus.ccrm.sms.aicall.vo.AiCallItemVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.UUID;

/**
 * @Author： Yaohui
 * @Date： 2025/4/28 11:19
 * @Describe：
 */
@Slf4j
@Service
public class AiCallService {

    @Value("${aicall.api.url.collection}")
    private String aicallApiUrlCollection;
    @Value("${aicall.auth.appkey.collection}")
    public String aicallAppkeyCollection;
    @Value("${aicall.auth.appsecret.collection}")
    private String aicallAppsecretCollection;
    @Value("${aicall.auth.taskid.collection}")
    private String aicallTaskidCollection;

    @Value("${aicall.api.url.reminder}")
    private String aicallApiUrlReminder;
    @Value("${aicall.auth.appkey.reminder}")
    public String aicallAppkeyReminder;
    @Value("${aicall.auth.appsecret.reminder}")
    private String aicallAppsecretReminder;
    @Value("${aicall.auth.taskid.reminder}")
    private String aicallTaskidReminder;


    /**
     * YaoHui
     * 推送AICall名单示例
     *[
     * {
     *  "tag":"",
     *  "number":"",
     *  "properties":{
     *      "尊称":"先生"
     *  },
     *}
     *
     * ]
     */
    public int sendAi(String taskId,List<AiCallItemVo>list){
        String timestamp=String.valueOf(System.currentTimeMillis());

        String aicallAppkey="";
        String aicallAppsecret="";
        String aicallApiUrl="";
        if(aicallTaskidCollection.equals(taskId)){
            aicallApiUrl=aicallApiUrlCollection;
            aicallAppkey=aicallAppkeyCollection;
            aicallAppsecret=aicallAppsecretCollection;
        }else if(aicallTaskidReminder.equals(taskId)){
            aicallApiUrl=aicallApiUrlReminder;
            aicallAppkey=aicallAppkeyReminder;
            aicallAppsecret=aicallAppsecretReminder;
        }

//        String iv= AiCallAESUtil.genTimestampIV(timestamp);
        String sign=AiCallAESUtil.getSign(aicallAppkey,aicallAppsecret,timestamp);
        String url=aicallApiUrl;
        if(!url.endsWith("/")) url+="/";
        url+="v1/task/importTaskCustomer";

        JSONArray arrs=new JSONArray();
        for(AiCallItemVo itemVo : list){
            JSONObject obj=new JSONObject();
            obj.put("tag",itemVo.getCaseid());
            obj.put("number",itemVo.getPhone());
//            JSONObject properties=new JSONObject();
//            properties.put("客户姓名","先生");
//            properties.put("逾期天数","10");
//            properties.put("逾期金额","1.0");
//            properties.put("业务品种","");
            obj.put("properties",itemVo.getContent());
            arrs.add(obj);
        }
        JSONObject bodyJson=new JSONObject();

        bodyJson.put("requestId", UUID.randomUUID());
        bodyJson.put("taskId", taskId);// 288684、288685
//        bodyJson.put("failReturn", "1");
        bodyJson.put("customers", arrs);
        String requestBody=bodyJson.toJSONString();

        log.debug("requestBody:{}",requestBody);
        try {
            HttpResponse<String> jsonResponse = Unirest.put(url)
                    .header("appKey", aicallAppkey)
                    .header("timestamp", timestamp)
                    .header("sign", sign)
                    .header("Content-Type", "application/json;charset=UTF-8")
                    .header("Accept", "application/json;")
//                    .header("encrypt","AES/CBC/PKCS5PADDING")
                    .body(requestBody)
                    .asString();

            int status = jsonResponse.getStatus();
            if (status == 200) {
                String respBody = jsonResponse.getBody();
                log.info("sendAi.Response:{}", respBody);
                String code = JSONObject.parseObject(jsonResponse.getBody().toString()).get("code").toString();
                if(code.equals("200")){
                    return 1;
                }
                return 0;
            }else{
                log.info("sendAiList.RespFail:status={},{}", jsonResponse.getStatus(),jsonResponse.getStatusText());
//                return new CmdResVo(status,String.format("请求失败:Code=%d",jsonResponse.getStatus()));
                return 0;
            }
        } catch (Exception e) {
            log.error("sendAiList",e);
//            return new CmdResVo(EnumRCode.CmdFail.value,EnumRCode.CmdFail.name+":"+e.getMessage());
            return -1;
        }
    }



//
//    public CmdResVo sendAiList(){
//        CmdResVo resVo=new CmdResVo();
//        String timestamp=String.valueOf(System.currentTimeMillis());
//
//
////        String requestBody=resVo.getKeyId();
//
//        String iv=AiCallAESUtil.genTimestampIV(timestamp);
//
//        String url=aicallApiUrl;
//        if(!url.endsWith("/")) url+="/";
//        url+="v1/task/importTaskCustomer";
//
//        try {
//            HttpResponse<String> jsonResponse = Unirest.put(url)
//                    .header("Content-Type", "application/json;charset=UTF-8")
//                    .header("encrypt","AES/CBC/PKCS5PADDING")
////                    .header("x-access-token", token)
//                    .header("appKey", aicallAppkey)
//                    .header("timestamp", timestamp)
////                    .body(requestBody)
//                    .asString();
//            int status = jsonResponse.getStatus();
//            if (status == 200) {
//                timestamp=getHeaderValue(jsonResponse.getHeaders(),"timestamp");
//                log.info("sendAiList.Response:timestamp={}", timestamp);
//                String respBody = jsonResponse.getBody();
//                log.info("sendAiList.Response:{}", respBody);
//                iv=AiCallAESUtil.genTimestampIV(timestamp);
//                resVo=AiCallAESUtil.cbcDecrypt(respBody,aicallAppsecret,iv);
//                if(JPubUtils.IsEqual(resVo.getCount(), EnumRCode.Success.value)){
//                    log.info("sendAiList.RespDecry:{}", resVo.getKeyId());
//                    JSONObject resp = JSONObject.parseObject(resVo.getKeyId());
//                    int code = resp.getInteger("code");
//                    String msg = resp.getString("message");
//                    return new CmdResVo(code, "AiCall:"+msg);
//                }else return resVo;
//            }else{
//                log.info("sendAiList.RespFail:status={},{}", jsonResponse.getStatus(),jsonResponse.getStatusText());
//                return new CmdResVo(status,String.format("请求失败:Code=%d",jsonResponse.getStatus()));
//            }
//        }catch (Exception e){
//            log.error("sendAiList",e);
//            return new CmdResVo(EnumRCode.CmdFail.value,EnumRCode.CmdFail.name+":"+e.getMessage());
//        }
//
//    }



    public static String getHeaderValue(Headers headers, String key)
    {
        List<String> list=headers.get(key);
        if(JPubUtils.IsEmpty(list)) return "";
        return list.get(0);
    }

    public CmdResVo getDecryptValue(String s,String timestamp,String appKey)
    {

        log.info("aicallAppkeyCollection:{},aicallAppkeyReminder:{}",aicallAppkeyCollection,aicallAppkeyReminder);
        String secret=null;
        if(aicallAppkeyCollection.equals(appKey)){
            secret=aicallAppsecretCollection;
        }else if(aicallAppkeyReminder.equals(appKey)){
            secret=aicallAppsecretReminder;
        }

        log.info("secret:{}",secret);

        return AiCallAESUtil.cbcDecrypt(s,secret,timestamp);
    }
}
